package com.example.controller;

import cn.novelweb.tool.upload.local.pojo.UploadFileParam;
import com.example.enums.ErrorCode;
import com.example.model.dto.AddFileInfo;
import com.example.model.response.RestResponse;
import com.example.model.response.RestResponseEntity;
import com.example.model.response.ServiceResult;
import com.example.service.FilesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("api/file")
public class FileUploadController {

    @Autowired
    private FilesService filesService;

    /**
     * 普通上传方式上传文件：用于小文件的上传，等待时间短，不会产生配置数据
     *
     * @param file 文件
     * @return 返回结果对象
     */
    @PostMapping("/uploadFiles")
    public RestResponse<String> uploadFiles(MultipartFile file) {
        if (file.isEmpty()) {
            return RestResponseEntity.newFailResponse(ErrorCode.INVALID_PARAMETER, "文件不能为空！");
        }
        ServiceResult<String> serviceResult = filesService.uploadFiles(file);
        return RestResponseEntity.newResponseFromServiceResult(serviceResult);
    }


    /**
     * 检查文件MD5，若存在则进行秒传
     *
     * @param md5      MD5
     * @param fileName 文件名
     * @return 返回结果对象
     */
    @GetMapping("/checkFileMd5")
    public RestResponse<Object> checkFileMd5(String md5, String fileName) {
        ServiceResult<Object> serviceResult = filesService.checkFileMd5(md5, fileName);
        return RestResponseEntity.newResponseFromServiceResult(serviceResult);

    }


    /**
     * 断点续传方式上传文件：用于大文件上传
     *
     * @param param   封装了文件上传相关的参数，例如：文件名、文件大小、当前分片索引、总分片数等
     * @param request 请求
     * @return 返回结果对象
     */
    @PostMapping(value = "/breakpointUpload")
    public RestResponse<Object> breakpointResumeUpload(UploadFileParam param, HttpServletRequest request) {
        ServiceResult<Object> serviceResult = filesService.breakpointResumeUpload(param, request);
        return RestResponseEntity.newResponseFromServiceResult(serviceResult);
    }


    /**
     * 添加文件信息到数据库
     *
     * @param addFileInfo 文件信息
     * @return 返回结果对象
     */
    @PostMapping("/add")
    public RestResponse<String> addFile(@RequestBody AddFileInfo addFileInfo) {
        ServiceResult<String> serviceResult = filesService.addFile(addFileInfo);
        return RestResponseEntity.newResponseFromServiceResult(serviceResult);
    }
}
